package com.itrip.biz.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itrip.beans.pojo.*;
import com.itrip.beans.vo.OrderInfoVo;
import com.itrip.beans.vo.PageVo;
import com.itrip.beans.vo.PersonalOrderRoomVO;
import com.itrip.biz.service.HotelOrderService;
import com.itrip.dao.HotelOrderMapper;
import com.itrip.dao.HotelRoomMapper;
import com.itrip.dao.OrderLinkUserMapper;
import com.itrip.utils.util.BigDecimalUtil;
import com.itrip.utils.util.EmptyUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.math.BigDecimal.ROUND_DOWN;

@Service
public class HotelOrderServiceImpl extends ServiceImpl<HotelOrderMapper, HotelOrder> implements HotelOrderService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource
    HotelOrderMapper hotelOrderMapper;

    @Resource
    HotelRoomMapper hotelRoomMapper;
    @Resource
    private OrderLinkUserMapper orderLinkUserMapper;

    @Override
    public PageVo getOrderInfo(T orderS, HttpServletRequest request) {
        String token=request.getHeader("token");
        int orderType = Integer.parseInt(orderS.getOrderType());
        QueryWrapper<HotelOrder> hotelOrderQueryWrapper = new QueryWrapper<HotelOrder>();
        hotelOrderQueryWrapper.eq("user_id",Integer.parseInt(stringRedisTemplate.opsForValue().get(token)));
        hotelOrderQueryWrapper.eq(orderS.getOrderStatus()>=0,"order_status", orderS.getOrderStatus());
        hotelOrderQueryWrapper.eq(orderType>=0,"order_type", orderS.getOrderType());
        hotelOrderQueryWrapper.like(orderS.getOrderNo()!=null,"order_no", orderS.getOrderNo());
        hotelOrderQueryWrapper.like(orderS.getLinkUserName()!=null,"link_user_name", orderS.getLinkUserName());
        hotelOrderQueryWrapper.like(orderS.getStartDate()!=null,"check_in_date", orderS.getStartDate());
        hotelOrderQueryWrapper.like(orderS.getEndDate()!=null,"check_out_date", orderS.getEndDate());
        Page<HotelOrder> page = new Page<>(orderS.getPageNo(),orderS.getPageSize());
        IPage<HotelOrder> orderF= hotelOrderMapper.selectPage(page,hotelOrderQueryWrapper);
        PageVo pageVo=new PageVo(orderS.getPageNo(),orderS.getPageSize(),(int)orderF.getTotal());
        pageVo.setRows(orderF.getRecords());
        return pageVo;
    }

    @Override
    public OrderInfoVo getOrderInfoDetails(int id) {
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        HotelOrder hotelOrder= hotelOrderMapper.selectById(id);
        orderInfoVo.setId(hotelOrder.getId());
        orderInfoVo.setBookType(hotelOrder.getBookType());
        orderInfoVo.setCreationDate(hotelOrder.getCreationDate());
        orderInfoVo.setNoticePhone(hotelOrder.getNoticePhone());
        orderInfoVo.setOrderNo(hotelOrder.getOrderNo());
        if (hotelOrder.getOrderStatus() == 1) {
            orderInfoVo.setOrderProcess("订单取消");
            orderInfoVo.setProcessNode("3");
        } else if (hotelOrder.getOrderStatus() == 0) {
            orderInfoVo.setOrderProcess("待支付");
            orderInfoVo.setProcessNode("2");//订单支付
        } else if (hotelOrder.getOrderStatus() == 2) {
            orderInfoVo.setOrderProcess("已支付");
            orderInfoVo.setProcessNode("3");//支付成功（未出行）
        } else if (hotelOrder.getOrderStatus() == 3) {
            orderInfoVo.setOrderProcess("已消费");
            orderInfoVo.setProcessNode("5");//订单点评
        } else if (hotelOrder.getOrderStatus() == 4) {
            orderInfoVo.setOrderProcess("已点评");
            orderInfoVo.setProcessNode("6");//订单完成
        }
        orderInfoVo.setOrderStatus(hotelOrder.getOrderStatus());
        orderInfoVo.setPayAmount(hotelOrder.getPayAmount());
        orderInfoVo.setPayType(hotelOrder.getPayType());
        HotelRoom hotelRoom= hotelRoomMapper.selectById(hotelOrder.getRoomId());
        orderInfoVo.setRoomPayType(hotelRoom.getPayType());
        return orderInfoVo;
    }

    @Override
    public BigDecimal getOrderPayAmount(int count, Long roomId) throws Exception {
        BigDecimal payAmount = null;
        BigDecimal roomPrice = hotelRoomMapper.selectById(roomId).getRoomPrice();
        payAmount = BigDecimalUtil.OperationASMD(count, roomPrice,
                BigDecimalUtil.BigDecimalOprations.multiply,
                2, ROUND_DOWN);
        return payAmount;
    }

    @Override
    public Map<String, String> itriptxAddItripHotelOrder(HotelOrder itripHotelOrder, List<UserLinkUser> linkUserList) throws Exception {
        //定义变量map，里面存放订单的id和orderNo返回给前端
        Map<String, String> map = new HashMap<String, String>();
        if (null != itripHotelOrder) {
            int flag=0;
            if (EmptyUtils.isNotEmpty(itripHotelOrder.getId())) {
                //删除联系人
                orderLinkUserMapper.deleteById(itripHotelOrder.getId());
                itripHotelOrder.setModifyDate(new Date());
                flag=hotelOrderMapper.updateById(itripHotelOrder);
            } else {
                itripHotelOrder.setCreationDate(new Date());
                flag=hotelOrderMapper.insert(itripHotelOrder);
            }
            if (flag > 0) {
                Long orderId = itripHotelOrder.getId();
                //添加订单之后还需要往订单与常用联系人关联表中添加记录
                if (orderId > 0) {
                    for (UserLinkUser itripUserLinkUser : linkUserList) {
                        OrderLinkUser itripOrderLinkUser = new OrderLinkUser();
                        itripOrderLinkUser.setOrderId(orderId);
                        itripOrderLinkUser.setLinkUserId(itripUserLinkUser.getId());
                        itripOrderLinkUser.setLinkUserName(itripUserLinkUser.getLinkUserName());
                        itripOrderLinkUser.setCreationDate(new Date());
                        itripOrderLinkUser.setCreatedBy(itripHotelOrder.getCreatedBy());
                        orderLinkUserMapper.insert(itripOrderLinkUser);
                    }
                }
                map.put("id", itripHotelOrder.getId().toString());
                map.put("orderNo", itripHotelOrder.getOrderNo());
                return map;
            }
        }
        return map;
    }

    @Override
    public PersonalOrderRoomVO getItripHotelOrderRoomInfoById(Long orderId) throws Exception {
        return hotelOrderMapper.getItripHotelOrderRoomInfoById(orderId);
    }

    @Override
    public boolean flushOrderStatus(Integer type) throws Exception {
        Integer flag;
        if (type == 1) {
            flag = hotelOrderMapper.flushCancelOrderStatus();
        } else {
            flag = hotelOrderMapper.flushSuccessOrderStatus();
        }
        return flag > 0 ? true : false;
    }

}
